﻿@{
    Layout = null;
    // 1. 从ViewData获取订单数据（C#对象）
    var orderData = ViewData["OrderData"] as List<Model.OmPurchaseOrderForUpdate> ?? new List<Model.OmPurchaseOrderForUpdate>();
    var mainOrder = orderData.FirstOrDefault() ?? new Model.OmPurchaseOrderForUpdate();

    // 2. 关键：用Newtonsoft.Json强制序列化，处理特殊字符和空值（确保输出合法JSON字符串）
    var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings
    {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, // 忽略循环引用
        StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml, // 转义HTML特殊字符（如引号、换行）
        NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, // 忽略null值（避免解析报错）
        DateFormatString = "yyyy-MM-dd" // 日期统一格式（适配前端日期选择器）
    };

    // 3. 生成合法的JSON字符串（此时orderDataJson/mainOrderJson已是字符串，不是对象）
    string orderDataJson = Newtonsoft.Json.JsonConvert.SerializeObject(orderData, jsonSettings);
    string mainOrderJson = Newtonsoft.Json.JsonConvert.SerializeObject(mainOrder, jsonSettings);
}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>编辑订单</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>
    <style>
        .basicInfo {
            width: 82%;
            height: 600px;
            background-color: #fff;
            padding-top: 20px;
            margin-top: 30px;
            margin-left: 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .stockUpDetail {
            width: 82%;
            min-height: 530px;
            background-color: #fff;
            padding-top: 10px;
            margin-left: 20px;
            margin-top: 50px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .uploadAttachment {
            width: 82%;
            min-height: 450px;
            background-color: #fff;
            padding-top: 10px;
            margin-left: 20px;
            margin-top: 50px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .saveBlock {
            display: grid;
            place-items: center;
            position: sticky;
            bottom: 0;
            width: 100%;
            height: 60px;
            background-color: #fff;
            z-index: 20;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .titleH {
            margin-left: 40px;
        }

        .orderTable {
            margin: 0 auto;
            width: 80%;
            border-spacing: 0 40px;
        }

        .imp {
            color: red;
        }

        .orderTable tbody tr td {
            border-spacing: 0 20px;
        }

        .custom-readonly-input .el-input__inner {
            background-color: #f0f0f0 !important;
            padding: 0px;
        }

        .custom-readonly-input .el-input__wrapper {
            background-color: #f0f0f0 !important;
        }

        /* 树控件样式优化 */
        .el-tree {
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            padding: 10px;
            max-height: 400px;
            overflow-y: auto;
        }

        .tree-title {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .detailBlock {
            padding-left: 30px;
        }

        .uploadAttach {
            padding-top: 30px;
            padding-left: 60px;
        }

        .searchBlock {
            display: inline;
        }

        .buttonBlock {
            display: inline;
            margin-left: 335px;
        }

        /* 合计行样式优化 */
        .el-table__footer-wrapper {
            font-weight: bold;
            background-color: #f5f7fa;
        }

            .el-table__footer-wrapper td {
                text-align: center !important;
            }

        .promptWord {
            color: #606266;
        }

        .upload-demo {
            display: inline-block;
        }

        .btnBlock {
            margin-left: auto;
            padding: 10px 20px 10px 10px;
        }

        .pagination-container {
            margin-left: 45%;
        }

        .valueV {
            color: orangered;
            font-weight: bolder;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout">
        <div class="basicInfo">
            <h2 class="titleH">基础信息</h2>
            <hr />
            <div class="basicInfoForm">
                <table class="orderTable">
                    <tbody>
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;进货单号
                            </td>
                            <td>
                                <el-input type="text" v-model="purchaseOrderCode" style="width:80%;" readonly placeholder="自动生成单号"></el-input>
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;进货日期
                            </td>
                            <td>
                                <el-date-picker type="date"
                                                placeholder="请选择日期"
                                                style="width:80%;"
                                                v-model="purchaseDate"
                                                value-format="YYYY-MM-DD" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;供应商
                            </td>
                            <td>
                                <el-select placeholder="请选择"
                                           style="width:80%;"
                                           v-model="selectedSupplierId"
                                           v-on:change="handleSupplierChange">
                                    <el-option v-for="supplier in supplierList"
                                               :key="supplier.supplierId"
                                               :label="supplier.supplierName"
                                               :value="supplier.supplierId" />
                                </el-select>
                                <el-button style="border:0px;color:limegreen">设置</el-button>
                            </td>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系人
                            </td>
                            <td>
                                <el-input placeholder="请输入" v-model="contactPerson" readonly style="width:80%;" class="custom-readonly-input"></el-input>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系方式
                            </td>
                            <td>
                                <el-input placeholder="请输入" v-model="contactPhone" readonly style="width:80%;" class="custom-readonly-input"></el-input>
                            </td>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;进货部门
                            </td>
                            <td v-on:click="stockInDepart = true">
                                <el-input placeholder="请选择"
                                          v-model="selectedDepart"
                                          style="width:80%"
                                          readonly></el-input>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;进货人
                            </td>
                            <td v-on:click="openManModal">
                                <el-input placeholder="请选择"
                                          v-model="selectedManName"
                                          style="width:83%"
                                          readonly></el-input>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注
                            </td>
                            <td colspan="3">
                                <el-input v-model="remarks" type="textarea" rows="5" placeholder="请输入" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="stockUpDetail">
            <h2 class="titleH">进货明细</h2>
            <hr />
            <div class="detailBlock">
                <div class="addAndRemove">
                    <el-button type="success" v-on:click="openAddGoodsDialog">添加</el-button>&nbsp;&nbsp;&nbsp;
                    <el-button type="danger" v-on:click="removeGoodsDetail">移除</el-button>
                </div>
                <div class="detailTable">
                    <el-table :data="goodsDetailData"
                              style="width: 1600px; margin-top: 10px"
                              v-on:selection-change="handleSelectionChange('detail', $event)"
                              ref="detailTable"
                              stripe>
                        <el-table-column fixed type="selection" width="50"></el-table-column>
                        <el-table-column fixed prop="id" label="序号" width="70"></el-table-column>
                        <!-- 货品名称：对应goodsName -->
                        <el-table-column fixed prop="goodsName" label="货品名称" width="100"></el-table-column>
                        <!-- 货品编号：对应goodsCode -->
                        <el-table-column fixed prop="goodsCode" label="货品编号" width="150"></el-table-column>
                        <!-- 规格型号：对应specification -->
                        <el-table-column prop="specification" label="规格型号" width="100"></el-table-column>
                        <!-- 单位：对应unit -->
                        <el-table-column prop="unit" label="单位" width="80">吨</el-table-column>
                        <!-- 货品类型：对应category -->
                        <el-table-column prop="goodsTypeName" label="货品类型" width="120"></el-table-column>
                        <!-- 当前库存：对应availableInventoryQty -->
                        <el-table-column prop="availableInventoryQty" label="当前库存" width="100" :formatter="formatNumber"></el-table-column>
                        <!-- 货品数量：手动输入 -->
                        <el-table-column prop="purchaseQuantity" label="货品数量" width="120">
                            <template #default="scope">
                                <el-input v-model.number="scope.row.purchaseQuantity"
                                          placeholder="请输入数量"
                                          style="width: 100%"
                                          v-on:input="handleNumberInput('purchaseQuantity', scope.row)"
                                          v-on:blur="validateNumber('purchaseQuantity', scope.row)"
                                          clearable></el-input>
                            </template>
                        </el-table-column>
                        <!-- 进货单价：对应purchaseReferencePrice -->
                        <el-table-column prop="purchasePrice" label="进货单价(元)" width="120">
                            <template #default="scope">
                                <el-input v-model.number="scope.row.purchasePrice"
                                          placeholder="请输入单价"
                                          style="width: 100%"
                                          v-on:input="handleNumberInput('purchasePrice', scope.row)"
                                          v-on:blur="validateNumber('purchasePrice', scope.row)"
                                          clearable></el-input>
                            </template>
                        </el-table-column>
                        <!-- 金额：自动计算 -->
                        <el-table-column prop="amount" label="金额" width="120" :formatter="formatNumber"></el-table-column>
                        <!-- 备注 -->
                        <el-table-column prop="remarks" label="备注" width="200">
                            <template #default="scope">
                                <el-input type="textarea"
                                          v-model="scope.row.remarks"
                                          placeholder="请输入备注"
                                          :rows="3"
                                          style="width: 100%"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" min-width="180">
                            <template #default="scope">
                                <el-button class="operate-btn"
                                           link type="primary" size="default"
                                           v-on:click="removeDetail(scope.row)">
                                    移除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="fixed-full-row" style="border-bottom:1px solid #f0f0f0;height:28px;padding:10px 0px">
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="promptWord">合计</span>
                        <div class="countNum" style="display:inline-block;margin-left:900px">
                            <span class="promptWord">货品种类: <span class="valueV">{{ totalCategories }}</span></span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span class="promptWord">货品数量: <span class="valueV">{{ totalQuantity }}</span>吨</span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span class="promptWord">总金额: <span class="valueV">{{ formatNumber(null, null, totalAmount) }}</span>元</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="uploadAttachment">
            <h2 class="titleH">上传附件</h2>
            <hr />
            <div class="uploadAttach">
                <!-- 文件选择组件（仅负责选择，不上传） -->
                <el-upload class="upload-demo"
                           action=""
                           name="files"
                           :file-list="tempFileList"
                           :auto-upload="false"
                           :show-file-list="false"
                           accept=".doc,.docx,.pdf,.rar,.zip"
                           :limit="10"
                           :on-exceed="handleFileExceed"
                           :on-change="handleFileSelect">
                    <el-button type="primary">选择文件</el-button>
                </el-upload>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span class="promptWord">支持格式：doc,docx,pdf,rar,zip | 单个文件≤200MB | 最多10个文件</span>

                <!-- 自定义文件列表（仅显示文件名） -->
                <div class="attachmentFile" style="margin-top: 20px;">
                    <div v-for="(file, index) in tempFileList"
                         :key="file.uid"
                         class="file-item"
                         style="width:60%;display: flex; align-items: center; margin: 10px 0; padding: 8px; border: 1px solid #eee; border-radius: 4px;">
                        <span style="flex: 1;">{{ file.name }}</span>
                        <el-button size="small"
                                   type="text"
                                   style="color: #ff4d4f;"
                                   v-on:click="removeTempFile(index)">
                            删除
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
        <div class="saveBlock">
            <div class="btnBlock">
                <el-button v-on:click="closeDetail">关闭</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveAsDraft">保存草稿</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button type="success" v-on:click="saveThis">保存修改</el-button>
            </div>
        </div>

        @* 进货部门选择模态框（增加搜索功能）*@
        <el-dialog v-model="stockInDepart" :modal="false" style="width:400px">
            <h3>选择部门</h3>
            <hr />
            <br />
            <!-- 部门搜索框 -->
            <el-input v-model="departSearchKey"
                      placeholder="请输入部门名称搜索"
                      class="search-input"
                      clearable>
                <template #prefix>
                    <el-icon class="el-input__icon"><Search /></el-icon>
                </template>
            </el-input>
            <br />
            <br />
            <div class="tree-container">
                <el-tree style="max-width: 300px"
                         :data="filteredDepartData"
                         :props="defaultProps"
                         :expand-on-click-node="false"
                         :default-expanded-keys="[1]"
                         v-on:node-click="departNode" />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="stockInDepart = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmDepart">确定</el-button>
                </div>
            </template>
        </el-dialog>

        @* 选择进货人员模态框（增加搜索功能）*@
        <el-dialog v-model="stockInMan" :modal="false" style="width:400px">
            <h3>选择人员</h3>
            <hr />
            <br />
            <!-- 人员搜索框 -->
            <el-input v-model="manSearchKey"
                      placeholder="请输入人员姓名搜索"
                      class="search-input"
                      clearable>
                <template #prefix>
                    <el-icon class="el-input__icon"><Search /></el-icon>
                </template>
            </el-input>
            <br />
            <h3>所属部门：{{ selectedOrgName || '未选择部门' }}</h3>
            <el-select v-model="selectedMan"
                       placeholder="请选择人员"
                       style="width: 100%"
                       v-on:change="confirmMan">
                <el-option v-for="man in searchFilteredManData"
                           :key="man.usersId"
                           :label="man.usersTrueName"
                           :value="man.usersId">
                </el-option>
            </el-select>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="stockInMan = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmMan">确定</el-button>
                </div>
            </template>
        </el-dialog>

        @* 添加货品模态框 *@
        <el-dialog v-model="addGoodsDialog" :modal="false" style="width:800px">
            <h3>添加货品</h3>
            <div class="addDetailsMain">
                <!-- 搜索区域 -->
                <div class="searchBlock">
                    <el-input type="text"
                              placeholder="请输入货品编号/名称"
                              style="width:300px"
                              v-model="goodsSearchKey"
                              clearable
                              v-on:keyup.enter="searchGoods">
                    </el-input>
                </div>
                <div class="buttonBlock">
                    <el-button v-on:click="resetGoodsSearch">重置</el-button>
                    <el-button type="success" v-on:click="searchGoods">查询</el-button>
                </div>

                <!-- 货品表格 -->
                <div class="goodsDetailTable">
                    <el-table :data="paginatedGoodsData"
                              style="width: 100%; margin-top: 10px"
                              v-on:selection-change="handleSelectionChange('add', $event)"
                              ref="addTable"
                              stripe>
                        <el-table-column type="selection" width="50"></el-table-column>
                        <!-- 序号列：自动计算（当前页-1）*页大小 + 索引 + 1 -->
                        <el-table-column label="序号" width="70">
                            <template #default="scope">
                                {{ (goodsCurrentPage - 1) * goodsPageSize + scope.$index + 1 }}
                            </template>
                        </el-table-column>
                        <!-- 货品编号 -->
                        <el-table-column prop="goodsCode" label="货品编号" width="100"></el-table-column>
                        <!-- 货品名称 -->
                        <el-table-column prop="goodsName" label="货品名称" width="150"></el-table-column>
                        <!-- 规格型号 -->
                        <el-table-column prop="specification" label="规格型号" width="100"></el-table-column>
                        <!-- 单位 -->
                        <el-table-column prop="unit" label="单位" width="80">吨</el-table-column>
                        <!-- 入库单价 -->
                        <el-table-column prop="purchaseReferencePrice"
                                         label="入库单价(元)"
                                         width="120"
                                         :formatter="formatNumber">
                        </el-table-column>
                        <!-- 当前库存 -->
                        <el-table-column prop="availableInventoryQty"
                                         label="当前库存"
                                         width="100"
                                         :formatter="formatNumber">
                        </el-table-column>
                    </el-table>
                    <!-- 分页组件（核心修改：与主页面分页逻辑对齐） -->
                    <div class="pagination-container" style="margin-top: 16px;">
                        <el-pagination v-model:current-page="goodsCurrentPage"
                                       v-model:page-size="goodsPageSize"
                                       :page-sizes="[10, 20, 50, 100]"
                                       :total="goodsTotal"
                                       layout="total, sizes, prev, pager, next, jumper"
                                       v-on:size-change="handleGoodsPageSizeChange"
                                       v-on:current-change="handleGoodsPageChange">
                        </el-pagination>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="addGoodsDialog = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmAddGoods">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, onMounted, computed, watchEffect } = Vue;
        const { ElMessageBox, ElMessage, ElIcon, Search } = ElementPlus;
        const app = createApp({
            components: {
                ElIcon,
                Search
            },
            setup() {
                // 模态框控制变量
                const stockInDepart = ref(false);
                const stockInMan = ref(false);
                const addGoodsDialog = ref(false);

                // 基础信息变量
                const purchaseDate = ref('');
                const selectedDepart = ref('');
                const selectedMan = ref('');
                const selectedManName = ref('');
                const currentDepart = ref(null);
                const selectedOrgName = ref('');
                const selectedDepartOrgId = ref(null);
                const flatDepartList = ref([]);
                const filteredManData = ref([]);
                const selectedManId = ref('');
                const remarks = ref('');
                const upOrderId = ref('');
                const purchaseOrderCode = ref('');

                // 搜索关键词
                const departSearchKey = ref('');
                const manSearchKey = ref('');

                // 供应商相关
                const supplierList = ref([]);
                const selectedSupplierId = ref('');
                const contactPerson = ref('');
                const contactPhone = ref('');

                // 当前登录用户ID
                const getCurrentUserId = () => {
                    const userStr = sessionStorage.getItem('YH');
                    if (!userStr) {
                        ElMessage.warning('未检测到登录状态，请重新登录');
                        return '';
                    }
                    try {
                        const userObj = JSON.parse(userStr);
                        return userObj?.id?.toString() || '';
                    } catch (error) {
                        console.error('解析用户信息失败：', error);
                        ElMessage.error('用户信息异常，请重新登录');
                        return '';
                    }
                };
                const currentUserId = ref(getCurrentUserId());

                // 货品相关
                const goodsCurrentPage = ref(1);
                const goodsPageSize = ref(10);
                const allGoodsData = ref([]);
                const goodsSearchKey = ref('');
                const addTable = ref(null);
                const goodsDetailData = ref([]);

                // 部门与人员数据
                const departData = ref([]);
                const manData = ref([]);
                const defaultProps = ref({
                    children: 'children',
                    label: 'label'
                });

                // 选中行数据
                const selectedRows = {
                    detail: ref([]),
                    add: ref([])
                };

                // 附件相关
                const tempFileList = ref([]);

                // 日期验证
                const validateDate = () => {
                    if (!purchaseDate.value) {
                        ElMessage.warning('请选择进货日期');
                        return false;
                    }
                    const today = new Date().toISOString().split('T')[0];
                    if (purchaseDate.value > today) {
                        ElMessage.warning('进货日期不能选择未来日期');
                        return false;
                    }
                    return true;
                };

                // 部门搜索过滤
                const filteredDepartData = computed(() => {
                    if (!departSearchKey.value) return departData.value;
                    const keyword = departSearchKey.value.toLowerCase();
                    const filterTree = (nodes) => {
                        return nodes
                            .filter(node => {
                                const matchSelf = node.name?.toLowerCase().includes(keyword) ||
                                                node.label?.toLowerCase().includes(keyword);
                                const filteredChildren = filterTree(node.children || []);
                                return matchSelf || filteredChildren.length > 0;
                            })
                            .map(node => ({
                                ...node,
                                children: filterTree(node.children || [])
                            }));
                    };
                    return filterTree(departData.value);
                });

                // 部门选择相关
                const departNode = (data) => {
                    currentDepart.value = data;
                    selectedDepartOrgId.value = data.id;
                };

                const confirmDepart = () => {
                    if (currentDepart.value) {
                        selectedDepart.value = currentDepart.value.label;
                        selectedDepartOrgId.value = currentDepart.value.id;
                        selectedOrgName.value = currentDepart.value.label;
                        filteredManData.value = manData.value.filter(man =>
                            man && String(man.orgId) === String(selectedDepartOrgId.value)
                        );
                    } else {
                        selectedDepart.value = '';
                        selectedDepartOrgId.value = null;
                        selectedOrgName.value = '';
                        filteredManData.value = manData.value;
                        ElMessage.info('未选择部门，将显示所有人员');
                    }
                    stockInDepart.value = false;
                };

                // 人员搜索过滤
                const searchFilteredManData = computed(() => {
                    if (!manSearchKey.value) return filteredManData.value;
                    const keyword = manSearchKey.value.toLowerCase();
                    return filteredManData.value.filter(man =>
                        man.usersTrueName?.toLowerCase().includes(keyword)
                    );
                });

                // 人员选择相关
                const confirmMan = () => {
                    if (selectedMan.value) {
                        const selectedManObj = manData.value.find(man =>
                            man && man.usersId && String(man.usersId) === String(selectedMan.value)
                        );
                        if (!selectedManObj) {
                            ElMessage.error('未找到匹配的人员，请刷新页面重试');
                            stockInMan.value = false;
                            return;
                        }
                        selectedManId.value = selectedMan.value;
                        const manOrgId = selectedManObj.orgId;
                        if (!manOrgId) {
                            ElMessage.error('人员部门信息异常（未关联部门）');
                            stockInMan.value = false;
                            return;
                        }

                        // 修复：使用更健壮的部门匹配逻辑，兼容不同的部门ID字段名
                        const findDepartName = (nodes, targetOrgId) => {
                            for (const node of nodes) {
                                // 同时匹配id和orgId字段，增加兼容性
                                if (String(node.id) === String(targetOrgId) || String(node.orgId) === String(targetOrgId)) {
                                    return node;
                                }
                                if (node.children?.length) {
                                    const childDepart = findDepartName(node.children, targetOrgId);
                                    if (childDepart) return childDepart;
                                }
                            }
                            return null;
                        };

                        // 优先从树形部门数据中查找（更准确）
                        const matchedDepart = findDepartName(departData.value, manOrgId)
                            // 备选：从扁平列表查找
                            || flatDepartList.value.find(depart =>
                                depart && (String(depart.id) === String(manOrgId) || String(depart.orgId) === String(manOrgId))
                            );

                        if (matchedDepart) {
                            selectedDepart.value = matchedDepart.label;
                            selectedOrgName.value = matchedDepart.label;
                            selectedDepartOrgId.value = manOrgId;
                            filteredManData.value = manData.value.filter(man =>
                                man && man.orgId && String(man.orgId) === String(manOrgId)
                            );
                            selectedManName.value = selectedManObj.usersTrueName;
                        } else {
                            // 修复：即使部门未找到，也保留人员选择，避免用户操作丢失
                            selectedManName.value = selectedManObj.usersTrueName;
                            selectedDepart.value = `未知部门（ID: ${manOrgId}）`;
                            ElMessage.warning('未找到对应部门信息，但已保存人员选择');
                        }
                        stockInMan.value = false;
                    } else {
                        ElMessage.warning('请选择人员');
                    }
                };

                const openManModal = () => {
                    selectedOrgName.value = selectedDepart.value || '';
                    stockInMan.value = true;
                };

                // 供应商加载与选择
                const loadSuppliers = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetSupplierInfoForSelectTable');
                        supplierList.value = Array.isArray(res.data) ? res.data : [];
                    } catch (err) {
                        console.error('加载供应商失败：', err);
                        ElMessage.error('网络错误，无法加载供应商数据');
                        supplierList.value = [];
                    }
                };

                const handleSupplierChange = (supplierId) => {
                    const selectedSupplier = supplierList.value.find(item => item.supplierId === supplierId);
                    contactPerson.value = selectedSupplier?.contactPerson || '';
                    contactPhone.value = selectedSupplier?.contactPhone || '';
                };

                // 货品数据处理
                const filteredGoodsData = computed(() => {
                    if (!goodsSearchKey.value.trim()) return allGoodsData.value;
                    const keyword = goodsSearchKey.value.trim().toLowerCase();
                    return allGoodsData.value.filter(item =>
                        (item.goodsCode?.toLowerCase().includes(keyword) || false) ||
                        (item.goodsName?.toLowerCase().includes(keyword) || false)
                    );
                });

                const goodsTotal = computed(() => filteredGoodsData.value.length);

                const paginatedGoodsData = computed(() => {
                    const start = (goodsCurrentPage.value - 1) * goodsPageSize.value;
                    const end = start + goodsPageSize.value;
                    return filteredGoodsData.value.slice(start, end);
                });

                const loadGoodsData = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetAllGoodsInfoForAddGoods');
                        allGoodsData.value = res.data || [];
                        goodsCurrentPage.value = 1;
                    } catch (err) {
                        console.error('加载货品失败：', err);
                        ElMessage.error('网络错误，无法加载货品信息');
                    }
                };

                const handleGoodsPageChange = (val) => {
                    goodsCurrentPage.value = val;
                    if (addTable.value) {
                        addTable.value.clearSelection();
                    }
                };

                const handleGoodsPageSizeChange = (val) => {
                    goodsPageSize.value = val;
                    goodsCurrentPage.value = 1;
                };

                const searchGoods = () => {
                    goodsCurrentPage.value = 1;
                };

                const resetGoodsSearch = () => {
                    goodsSearchKey.value = '';
                    goodsCurrentPage.value = 1;
                };

                const openAddGoodsDialog = () => {
                    addGoodsDialog.value = true;
                };

                // 添加货品处理
                const confirmAddGoods = () => {
                    if (selectedRows.add.value.length === 0) {
                        ElMessage.warning("请先勾选要添加的货品");
                        return;
                    }

                    const existingGoodsMap = new Map();
                    goodsDetailData.value.forEach(item => {
                        existingGoodsMap.set(item.goodsCode, item);
                    });

                    const duplicateGoods = [];
                    const newGoods = [];

                    selectedRows.add.value.forEach(goods => {
                        if (existingGoodsMap.has(goods.goodsCode)) {
                            duplicateGoods.push(goods);
                        } else {
                            newGoods.push(goods);
                        }
                    });

                    if (duplicateGoods.length > 0) {
                        const duplicateNames = duplicateGoods.map(g => g.goodsName).join('、');
                        ElMessageBox.confirm(
                            `以下货品已在明细中：${duplicateNames}，是否将数量合并到现有行？`,
                            '重复提示',
                            {
                                confirmButtonText: '合并数量',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }
                        ).then(() => {
                            duplicateGoods.forEach(goods => {
                                const existingItem = existingGoodsMap.get(goods.goodsCode);
                                existingItem.purchaseQuantity = (existingItem.purchaseQuantity || 0) + 1;
                                existingItem.amount = (existingItem.purchaseQuantity * existingItem.purchasePrice).toFixed(2) * 1;
                            });
                            addNewGoods(newGoods);
                            finishAddOperation();
                        }).catch(() => {});
                        return;
                    }

                    addNewGoods(newGoods);
                    finishAddOperation();
                };

                const addNewGoods = (goodsList) => {
                    goodsList.forEach(goods => {
                        goodsDetailData.value.push({
                            id: goodsDetailData.value.length + 1,
                            goodsName: goods.goodsName,
                            goodsCode: goods.goodsCode,
                            specification: goods.specification,
                            unit: goods.unit || '吨',
                            goodsTypeName: goods.goodsTypeName || '',
                            availableInventoryQty: goods.availableInventoryQty || 0,
                            goodsTypeId: goods.goodsTypeId || 0,
                            purchaseQuantity: 1,
                            purchasePrice: goods.purchaseReferencePrice || 0,
                            amount: goods.purchaseReferencePrice || 0,
                            remarks: ''
                        });
                    });
                };

                const finishAddOperation = () => {
                    const totalAdded = selectedRows.add.value.length;
                    ElMessage.success(`已处理 ${totalAdded} 种货品`);
                    addGoodsDialog.value = false;
                    if (addTable.value) {
                        addTable.value.clearSelection();
                        selectedRows.add.value = [];
                    }
                };

                // 数值格式化
                const formatNumber = (row, column, cellValue) => {
                    if (cellValue === null || cellValue === undefined || isNaN(Number(cellValue))) {
                        return '0.00';
                    }
                    return Number(cellValue).toFixed(2);
                };

                // 合计计算
                const totalCategories = computed(() => {
                    const codes = new Set();
                    goodsDetailData.value.forEach(item => codes.add(item.goodsCode));
                    return codes.size;
                });

                const totalQuantity = computed(() => {
                    return goodsDetailData.value.reduce((sum, item) => {
                        return sum + (Number(item.purchaseQuantity) || 0);
                    }, 0);
                });

                const totalAmount = computed(() => {
                    return goodsDetailData.value.reduce((sum, item) => {
                        return sum + (Number(item.amount) || 0);
                    }, 0);
                });

                // 数量与单价输入处理
                const handleNumberInput = (field, row) => {
                    if (row[field] === null || row[field] === undefined) return;
                    let value = row[field].toString().replace(/[^\d.]/g, '');
                    value = value.replace(/\.{2,}/g, '.');
                    value = value.replace(/^0+(\d)/, '$1');
                    if (value.startsWith('.')) value = '0' + value;
                    row[field] = value === '' ? 0 : Number(value);
                };

                const validateNumber = (field, row) => {
                    const value = row[field];
                    if (value === null || value === undefined || isNaN(Number(value))) {
                        row[field] = 0;
                        ElMessage.warning(`${field === 'purchaseQuantity' ? '数量' : '单价'}不能为空，已自动设为0`);
                        return;
                    }
                    if (Number(value) < 0) {
                        row[field] = 0;
                        ElMessage.warning(`${field === 'purchaseQuantity' ? '数量' : '单价'}不能为负数，已自动设为0`);
                    }
                    row[field] = Number(Number(value).toFixed(2));
                };

                // 监听金额计算
                watchEffect(() => {
                    goodsDetailData.value.forEach(row => {
                        if (row) {
                            const qty = Number(row.purchaseQuantity) || 0;
                            const price = Number(row.purchasePrice) || 0;
                            row.amount = (qty * price).toFixed(2) * 1;
                        }
                    });
                });

                // 明细操作
                const handleSelectionChange = (tableType, val) => {
                    selectedRows[tableType].value = val;
                };

                const removeDetail = (row) => {
                    goodsDetailData.value = goodsDetailData.value.filter(item => item.id !== row.id);
                    setTimeout(() => ElMessage.success("已移除当前进货明细行"), 0);
                };

                const removeGoodsDetail = () => {
                    if (selectedRows.detail.value.length === 0) {
                        ElMessage.warning("请先勾选要移除的明细行");
                        return;
                    }
                    const removeCount = selectedRows.detail.value.length;
                    goodsDetailData.value = goodsDetailData.value.filter(
                        row => !selectedRows.detail.value.some(selected => selected.id === row.id)
                    );
                    selectedRows.detail.value = [];
                    setTimeout(() => ElMessage.success(`已批量移除 ${removeCount} 条明细`), 0);
                };

                // 附件处理
                const handleFileSelect = (file, fileList) => {
                    tempFileList.value = fileList;
                };

                const removeTempFile = (index) => {
                    tempFileList.value.splice(index, 1);
                    ElMessage.info('已移除选中文件');
                };

                const handleFileExceed = (files) => {
                    ElMessage.warning(`最多只能上传10个文件，本次超出${files.length}个`);
                };

                // 页面操作
                const closeDetail = () => {
                    window.location.href = '/StockUpOrder/Index';
                };

                const saveAsDraft = () => {
                    // 草稿保存逻辑可在此实现
                };

                const saveThis = async () => {
                    if (!upOrderId.value) {
                        ElMessage.warning('订单ID缺失，无法修改');
                        return;
                    }
                    if (!validateDate()) return;
                    if (!selectedSupplierId.value) {
                        ElMessage.warning('请选择供应商');
                        return;
                    }

                    const formData = new FormData();
                    const opof = {
                        UpOrderId: upOrderId.value,
                        UpOrderNo: purchaseOrderCode.value,
                        SupplierId: selectedSupplierId.value,
                        OrderStatus: '1',
                        BuyerBy: selectedManId.value,
                        CreateBy: currentUserId.value,
                        Remarks: remarks.value
                    };
                    formData.append('omPurchaseOrderForUpdate', JSON.stringify(opof));

                    const details = goodsDetailData.value.map(item => ({
                        UpOrderId: upOrderId.value,
                        GoodsCode: item.goodsCode || '',
                        GoodsTypeId: item.goodsTypeId || 0,
                        PurchaseUnitPrice: Number(item.purchasePrice) || 0,
                        OrderQuantity: Number(item.purchaseQuantity) || 0,
                        AttachmentCode: item.attachmentCode || '无',
                        Remarks: item.remarks || '无'
                    }));
                    formData.append('details', JSON.stringify(details));

                    if (tempFileList.value.length > 0) {
                        tempFileList.value.forEach(file => {
                            if (file.raw) {
                                formData.append('files', file.raw);
                            }
                        });
                    }

                    try {
                        const response = await axios.post('/StockUpOrder/UpdateOmPurOrderFunc', formData, {
                            headers: { 'Content-Type': 'multipart/form-data' }
                        });

                        if (response.data.success) {
                            ElMessage.success('订单修改成功');
                            setTimeout(() => {
                                window.location.href = '/StockUpOrder/Index';
                            }, 1500);
                        } else {
                            ElMessage.error(`修改失败：${response.data.message || '未知错误'}`);
                        }
                    } catch (err) {
                        console.error('修改提交异常：', err);
                        ElMessage.error('网络错误，请重试');
                    }
                };

                // 加载人员数据
                const loadManData = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetUserInfoForSelectTable');
                        manData.value = (res.data || []).filter(man => man?.usersId && man?.orgId);
                        filteredManData.value = manData.value;
                    } catch (err) {
                        console.error('加载人员列表失败：', err);
                        ElMessage.error('人员数据加载失败，可能影响进货人回显');
                    }
                };

                // 加载部门数据
                const loadDepartData = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetOrgInfoForSelectTable');
                        departData.value = Array.isArray(res.data) ? res.data : [];
                        const flattenDepart = (arr) => arr.reduce((acc, item) => {
                            acc.push(item);
                            if (item.children?.length) acc.push(...flattenDepart(item.children));
                            return acc;
                        }, []);
                        flatDepartList.value = flattenDepart(departData.value);
                    } catch (err) {
                        console.error('加载部门列表失败：', err);
                        ElMessage.error('部门数据加载失败，可能影响进货部门回显');
                    }
                };

                // 初始化
                onMounted(async () => {
                    const mainOrder = @Html.Raw(mainOrderJson);
                    const orderDetails = @Html.Raw(orderDataJson);
                    await Promise.all([
                        loadManData(),
                        loadDepartData(),
                        loadSuppliers(),
                        loadGoodsData()
                    ]);

                    if (mainOrder) {
                        upOrderId.value = mainOrder.UpOrderId || '';
                        purchaseOrderCode.value = mainOrder.UpOrderNo || '';
                        purchaseDate.value = mainOrder.BuyerDate ? new Date(mainOrder.BuyerDate).toISOString().split('T')[0] : '';
                        selectedSupplierId.value = mainOrder.SupplierId || '';
                        remarks.value = mainOrder.OmPORemarks || '';

                        const buyerId = mainOrder.BuyerBy;
                        if (buyerId) {
                            const matchedMan = manData.value.find(man => man?.usersId === buyerId);
                            if (matchedMan) {
                                selectedManId.value = buyerId;
                                selectedManName.value = matchedMan.usersTrueName || '未知人员';
                                const manOrgId = matchedMan.orgId;
                                if (manOrgId) {
                                    const findDepartName = (nodes, targetOrgId) => {
                                        for (const node of nodes) {
                                            if (node.id === targetOrgId) return node.label;
                                            if (node.children?.length) {
                                                const childDepartName = findDepartName(node.children, targetOrgId);
                                                if (childDepartName) return childDepartName;
                                            }
                                        }
                                        return '';
                                    };
                                    selectedDepart.value = findDepartName(departData.value, manOrgId) || '未知部门';
                                    selectedDepartOrgId.value = manOrgId;
                                }
                            } else {
                                selectedManName.value = '未找到对应进货人';
                                selectedDepart.value = '未关联部门';
                            }

                            const matchedSupplier = supplierList.value.find(s => s.supplierId === selectedSupplierId.value);
                            contactPerson.value = matchedSupplier?.contactPerson || '';
                            contactPhone.value = matchedSupplier?.contactPhone || '';
                        }
                    }

                    if (orderDetails.length > 0) {
                        // 先过滤掉GoodsCode为空或null的无效明细，再映射处理
                        goodsDetailData.value = orderDetails
                            .filter(item => {
                                // 仅保留GoodsCode不为空且不为null的条目
                                return item.GoodsCode != '' && item.GoodsCode != null;
                            })
                            .map((item, index) => {
                                const matchedGoods = allGoodsData.value.find(g => g.goodsCode === item.GoodsCode);
                                return {
                                    id: index + 1, // 注意：filter后index会重新计算，确保id连续
                                    goodsName: matchedGoods?.goodsName || '未知货品',
                                    goodsCode: item.GoodsCode || '',
                                    specification: matchedGoods?.specification || '',
                                    unit: matchedGoods?.unit || '吨',
                                    goodsTypeName: matchedGoods?.goodsTypeName || '',
                                    availableInventoryQty: matchedGoods?.availableInventoryQty || 0,
                                    goodsTypeId: item.GoodsTypeId || 0,
                                    purchaseQuantity: item.OrderQuantity || 0,
                                    purchasePrice: item.PurchaseUnitPrice || 0,
                                    amount: (item.OrderQuantity || 0) * (item.PurchaseUnitPrice || 0),
                                    remarks: item.OmPODRemarks || ''
                                };
                            });
                    }

                    const attachments = orderDetails
                        .filter(item => item.AttachmentAddress)
                        .map(item => ({
                            name: item.AttachmentName || `附件${item.AttachmentCode || ''}`,
                            url: item.AttachmentAddress || '',
                            uid: item.AttachmentCode || Date.now() + Math.random()
                        }));
                    const uniqueAttachments = Array.from(new Map(attachments.map(a => [a.uid, a])).values());
                    tempFileList.value = uniqueAttachments;
                });

                return {
                    currentUserId,
                    purchaseDate,
                    validateDate,
                    stockInDepart,
                    stockInMan,
                    addGoodsDialog,
                    selectedDepart,
                    selectedMan,
                    selectedManName,
                    departData,
                    manData,
                    defaultProps,
                    departNode,
                    confirmDepart,
                    confirmMan,
                    purchaseOrderCode,
                    selectedDepartOrgId,
                    flatDepartList,
                    filteredManData,
                    openManModal,
                    selectedOrgName,
                    remarks,
                    supplierList,
                    selectedSupplierId,
                    contactPerson,
                    contactPhone,
                    handleSupplierChange,
                    goodsCurrentPage,
                    goodsPageSize,
                    goodsTotal,
                    paginatedGoodsData,
                    goodsSearchKey,
                    loadGoodsData,
                    handleGoodsPageChange,
                    handleGoodsPageSizeChange,
                    searchGoods,
                    resetGoodsSearch,
                    openAddGoodsDialog,
                    confirmAddGoods,
                    formatNumber,
                    addTable,
                    totalCategories,
                    totalQuantity,
                    totalAmount,
                    goodsDetailData,
                    handleNumberInput,
                    validateNumber,
                    removeGoodsDetail,
                    handleSelectionChange,
                    selectedRows,
                    removeDetail,
                    departSearchKey,
                    manSearchKey,
                    filteredDepartData,
                    searchFilteredManData,
                    tempFileList,
                    handleFileSelect,
                    removeTempFile,
                    handleFileExceed,
                    saveAsDraft,
                    saveThis,
                    closeDetail
                };
            }
        });
        app.use(ElementPlus, {
            locale: ElementPlusLocaleZhCn
        });
        app.mount('#app');
    </script>
</body>
</html>

